#pragma once
#include "Comm.hpp"

#define PATH      "."
#define FILENAME  "fifo"

class NameFifo
{
public:
    NameFifo(const std::string &path, const std::string &name)
        :_path(path), _name(name)
    {
        _fifoname = _path + "/" + _name;
        // 给默认权限从0开始
        umask(0);
        // 创建管道
        int n = mkfifo(_fifoname.c_str(), 0666);
        if (n < 0)
        {
            // 创建管道失败
            ERR_EXIT("mkfifo");
        }
        else
        {
            println("mkfifo success!");
        }
    }
    ~NameFifo()
    {
        // 删除管道文件
        int n = unlink(_fifoname.c_str());
        if (n == 0)
            ERR_EXIT("unlink");
        else
            println("remove fifo failed!");
    }

private:
    std::string _path;
    std::string _name;
    std::string _fifoname; 
};

class fileOper
{
public:
    fileOper(const std::string &path, const std::string &name)
        :_path(path), _name(name), _fd(-1)
    {
        _fifoname = _path + "/" + _name;
    }
    void openForRead()
    {
        // 打开, 写入方没有执行open的时候, 读取方, 就要再open内部进行阻塞
        // 直到有人把管道文件打开了, open才会返回!
        _fd = open(_fifoname.c_str(), O_RDONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
        }
        println("open fifo success!");
    }
    void openForWrite()
    {
        // write 
        _fd = open(_fifoname.c_str(), O_WRONLY);
        if (_fd < 0)
        {
            ERR_EXIT("open");
        }
        println("open fifo suceess!");
    }
    void Wakeup()
    {
        // 写入操作
        char c = 'c';
        int n = write(_fd, &c, 1);
        println("尝试唤醒: {}", n);
    }
    bool Wait()
    {
        char c;
        int number = read(_fd, &c, 1);
        if (number > 0) {
            println("醒来: {}", number);
            return true;
        }
        return false;
    }
    void Close()
    {
        if (_fd > 0)
            close(_fd);
    }
    ~fileOper() {}
private:
    std::string _path;
    std::string _name;
    std::string _fifoname;
    int _fd;
};
